/*
# Rouleur Log - A log for cyclists.
# Copyright (C) 2006  Edward Copony (ecopony@gmail.com)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package com.blazingredfireball.rouleurlog.model
{
  import mx.collections.ICollectionView;
  import com.adobe.cairngorm.model.ModelLocator;
  import mx.collections.ArrayCollection;
  import com.blazingredfireball.rouleurlog.vo.RideVO;
  import com.blazingredfireball.rouleurlog.vo.BikeVO;
  import com.blazingredfireball.rouleurlog.vo.RouteVO;
  import com.blazingredfireball.rouleurlog.vo.UserVO;
  import flash.data.SQLConnection;
  import flash.events.SQLErrorEvent;
  import flash.filesystem.File;
  import flash.events.SQLEvent;
  import mx.controls.Alert;
  import flash.data.SQLStatement;

  [Bindable]
	public class RouleurlogModelLocator implements ModelLocator
	{
	  private static var modelLocator:RouleurlogModelLocator;
	  public var databaseConnection:SQLConnection;
	  public var databaseInitialized:Boolean = false;
	  
	  public static function getInstance() : RouleurlogModelLocator 
	  {
      if ( modelLocator == null )
      {
      	modelLocator = new RouleurlogModelLocator();
      }
      		
      return modelLocator;
    }

	  public function initializeDatabase():void
	  {
	    var connection:SQLConnection = new SQLConnection();
      var databaseFile:File = File.applicationStorageDirectory.resolvePath("RouleurLog.db");
      
      var isNewDatabase:Boolean = false;
       
      if (!databaseFile.exists) isNewDatabase = true;
      
      connection.addEventListener(SQLEvent.OPEN, function (event:SQLEvent):void
      {
        if (!isNewDatabase) databaseInitialized = true;
      });

      connection.addEventListener(SQLErrorEvent.ERROR, function (event:SQLErrorEvent):void
      {
        Alert.show("Error code:", event.error.code);
        Alert.show("Details:", event.error.message);
      });
      
      connection.open(databaseFile);
      databaseConnection = connection;
      
      if (isNewDatabase) createTables();
   }
      
    private function createTables():void
    {
      var statement:SQLStatement = new SQLStatement();
			statement.sqlConnection = databaseConnection;
			
			statement.addEventListener(SQLEvent.RESULT, createRoutes);
			statement.addEventListener(SQLErrorEvent.ERROR, createTableFault);
			
			statement.text = "" + 
        "CREATE TABLE IF NOT EXISTS bikes (" + 
        "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
        "name varchar(24), " + 
        "description text, " + 
        "created_on REAL, " + 
        "updated_on REAL)";
      statement.execute();
    }	  
	  
	  private function createRoutes(event:Object):void
	  {
	    var statement:SQLStatement = new SQLStatement();
			statement.sqlConnection = databaseConnection;
			
			statement.addEventListener(SQLEvent.RESULT, createRides);
			statement.addEventListener(SQLErrorEvent.ERROR, createTableFault);
			
			statement.text = "CREATE TABLE IF NOT EXISTS routes (" + 
			  "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
        "name varchar(24), " + 
        "description text, " + 
        "created_on REAL, " + 
        "updated_on REAL)";
      statement.execute();
	  }
	  
	  private function createRides(event:Object):void
	  {
	    var statement:SQLStatement = new SQLStatement();
			statement.sqlConnection = databaseConnection;
			
			statement.addEventListener(SQLEvent.RESULT, finalizeDatabaseCreation);
			statement.addEventListener(SQLErrorEvent.ERROR, createTableFault);
			
			statement.text = "CREATE TABLE rides (" + 
		    "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
			  "distance INTEGER, " + 
			  "comments text, " + 
			  "riding_time varchar(24), " + 
			  "average_speed REAL, " + 
			  "max_speed REAL, " + 
			  "route_id INTEGER, " + 
			  "bike_id INTEGER, " + 
			  "elevation_gain INTEGER, " + 
			  "ride_on REAL, " + 
			  "created_on REAL, " + 
			  "updated_on REAL)";
      statement.execute();
	  }
	  
	  private function finalizeDatabaseCreation(event:Object):void
	  {
	    databaseInitialized = true;
	  }
	  
	  private function createTableFault(event:Object):void
	  {
	    Alert.show("Error code:", event.error.code);
      Alert.show("Details:", event.error.message);
	  }
	  
    /**
		 * This doesn't really belong in the model. Just getting it in a central
		 * location for now.
		 */
		public function doSql(sql:String, responder:Object):void
		{
		  var statement:SQLStatement = new SQLStatement();
			statement.sqlConnection = databaseConnection;
      statement.text = sql;
      statement.addEventListener(SQLEvent.RESULT, responder.result);
      statement.addEventListener(SQLErrorEvent.ERROR, responder.fault);
      statement.execute();
		}
	  
	  //Constructor should be private but current AS3.0 does not allow it yet
    public function RouleurlogModelLocator() 
    {	
      if ( modelLocator != null )
      {
        throw new Error( "Only one RouleurlogModelLocator instance should be instantiated" );	
      }
    }
      
    public var viewState : String = MANAGE_RIDES_VIEW; 
    public static const MANAGE_RIDES_VIEW : String = "Manage Rides";
    public static const MANAGE_BIKES_VIEW : String = "Manage Bikes";
    public static const MANAGE_ROUTES_VIEW : String = "Manage Routes";
      
	  public var rides : ArrayCollection;
	  public var selectedRide : RideVO;
	  public var bikes : ArrayCollection;
	  public var selectedBike:BikeVO;
	  public var routes : ArrayCollection;
    public var selectedRoute : RouteVO;
	  public var user : UserVO;
	  public var theme:String = "silver";

   }
}